home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / oleo-1_4.lha / oleo-1.4 / sort.c < prev    next >
C/C++ Source or Header  |  1993-01-01  |  9KB  |  298 lines

  1. /*    Copyright (C) 1990, 1992, 1993 Free Software Foundation, Inc.
  2.  
  3. This file is part of Oleo, the GNU Spreadsheet.
  4.  
  5. Oleo is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. Oleo is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with Oleo; see the file COPYING.  If not, write to
  17. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. /* Plug-compatible replacement for UNIX qsort.
  20.    Copyright (C) 1989,1990, 1992, 1993 Free Software Foundation, Inc.
  21.    Written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  22.    Modified by Jay Fenlason for use in the spreadsheet. */
  23.  
  24. /* The modifications for the spreadsheet consist of calling functions to
  25.    compare, swap, and rotate array elements.  This allows it to work
  26.    on sparse arrays, where some or all of the elements may not exist
  27.  */
  28.  
  29. /* Envoke the comparison function, returns either 0, < 0, or > 0. */
  30. #define CMP(A,B) ((*cmp)((A),(B)))
  31.  
  32. /* Byte-wise swap two items of size SIZE. */
  33. /* #define SWAP(A,B,SIZE) do {int sz = (SIZE); char *a = (A); char *b = (B); \
  34.     do { char _temp = *a;*a++ = *b;*b++ = _temp;} while (--sz);} while (0) */
  35. #define SWAP(A,B) ((*swap)((A),(B)))
  36.  
  37. #define ROT(a,b) ((*rot)((a),(b)))
  38.  
  39. /* Copy SIZE bytes from item B to item A. */
  40. /* #define COPY(A,B,SIZE) {int sz = (SIZE); do { *(A)++ = *(B)++; } while (--sz); } */
  41.  
  42. /* This should be replaced by a standard ANSI macro. */
  43. #define BYTES_PER_WORD 8
  44.  
  45. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  46. #define STACK_SIZE (BYTES_PER_WORD * sizeof (long))
  47. #define PUSH(LOW,HIGH) do {top->lo = LOW;top++->hi = HIGH;} while (0)
  48. #define POP(LOW,HIGH)  do {LOW = (--top)->lo;HIGH = top->hi;} while (0)
  49. #define STACK_NOT_EMPTY (stack < top)
  50.  
  51. /* Discontinue quicksort algorithm when partition gets below this size.
  52.    This particular magic number was chosen to work best on a Sun 4/260. */
  53. #define MAX_THRESH 4
  54.  
  55. /* Stack node declarations used to store unfulfilled partition obligations. */
  56. typedef struct
  57. {
  58.   int lo;
  59.   int hi;
  60. }
  61.  
  62. stack_node;
  63.  
  64. /* Order size using quicksort.  This implementation incorporates
  65.    four optimizations discussed in Sedgewick:
  66.  
  67.    1. Non-recursive, using an explicit stack of pointer that store the
  68.       next array partition to sort.  To save time, this maximum amount
  69.       of space required to store an array of MAX_INT is allocated on the
  70.       stack.  Assuming a 32-bit integer, this needs only 32 *
  71.       sizeof (stack_node) == 136 bits.  Pretty cheap, actually.
  72.  
  73.    2. Chose the pivot element using a median-of-three decision tree.
  74.       This reduces the probability of selecting a bad pivot value and
  75.       eliminates certain extraneous comparisons.
  76.  
  77.    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  78.       insertion sort to order the MAX_THRESH items within each partition.
  79.       This is a big win, since insertion sort is faster for small, mostly
  80.       sorted array segements.
  81.  
  82.    4. The larger of the two sub-partitions is always pushed onto the
  83.       stack first, with the algorithm then concentrating on the
  84.       smaller partition.  This *guarantees* no more than log (n)
  85.       stack size is needed (actually O(1) in this case)! */
  86.  
  87. int
  88. sort (total_elems, cmp, swap, rot)
  89.      int total_elems;
  90.      int (*cmp) ();
  91.      void (*swap) ();
  92.      void (*rot) ();
  93. {
  94.   /* Allocating SIZE bytes for a pivot buffer facilitates a better
  95.      algorithm below since we can do comparisons directly on the pivot. */
  96.   int max_thresh = MAX_THRESH;
  97.  
  98.   if (total_elems > MAX_THRESH)
  99.     {
  100.       int lo = 0;
  101.       int hi = lo + (total_elems - 1);
  102.       stack_node stack[STACK_SIZE];    /* Largest size needed for 32-bit int!!! */
  103.       stack_node *top = stack + 1;
  104.  
  105.       while (STACK_NOT_EMPTY)
  106.     {
  107.       int left_ptr;
  108.       int right_ptr;
  109.       {
  110.         int pivot;
  111.         {
  112.           /* Select median value from among LO, MID, and HI. Rearrange
  113.                  LO and HI so the three values are sorted. This lowers the
  114.                  probability of picking a pathological pivot value and
  115.                  skips a comparison for both the LEFT_PTR and RIGHT_PTR. */
  116.  
  117.           int mid = lo + ((hi - lo) >> 1);
  118.  
  119.           if (CMP (mid, lo) < 0)
  120.         SWAP (mid, lo);
  121.           if (CMP (hi, mid) < 0)
  122.         SWAP (mid, hi);
  123.           else
  124.         goto jump_over;
  125.           if (CMP (mid, lo) < 0)
  126.         SWAP (mid, lo);
  127.         jump_over:
  128.           /* COPY (pivot, mid); */
  129.           pivot = mid;
  130.           /* pivot = pivot_buffer; */
  131.         }
  132.         left_ptr = lo + 1;
  133.         right_ptr = hi - 1;
  134.  
  135.         /* Here's the famous ``collapse the walls'' section of quicksort.
  136.                Gotta like those tight inner loops!  They are the main reason
  137.                that this algorithm runs much faster than others. */
  138.         do
  139.           {
  140.         while (CMP (left_ptr, pivot) < 0)
  141.           left_ptr += 1;
  142.  
  143.         while (CMP (pivot, right_ptr) < 0)
  144.           right_ptr -= 1;
  145.  
  146.         if (left_ptr < right_ptr)
  147.           {
  148.             SWAP (left_ptr, right_ptr);
  149.             left_ptr += 1;
  150.             right_ptr -= 1;
  151.           }
  152.         else if (left_ptr == right_ptr)
  153.           {
  154.             left_ptr += 1;
  155.             right_ptr -= 1;
  156.             break;
  157.           }
  158.           }
  159.         while (left_ptr <= right_ptr);
  160.  
  161.       }
  162.  
  163.       /* Set up pointers for next iteration.  First determine whether
  164.              left and right partitions are below the threshold size. If so,
  165.              ignore one or both.  Otherwise, push the larger partition's
  166.              bounds on the stack and continue sorting the smaller one. */
  167.  
  168.       if ((right_ptr - lo) <= max_thresh)
  169.         {
  170.           if ((hi - left_ptr) <= max_thresh)    /* Ignore both small partitions. */
  171.         POP (lo, hi);
  172.           else        /* Ignore small left partition. */
  173.         lo = left_ptr;
  174.         }
  175.       else if ((hi - left_ptr) <= max_thresh)    /* Ignore small right partition. */
  176.         hi = right_ptr;
  177.       else if ((right_ptr - lo) > (hi - left_ptr))    /* Push larger left partition indices. */
  178.         {
  179.           PUSH (lo, right_ptr);
  180.           lo = left_ptr;
  181.         }
  182.       else
  183.         /* Push larger right partition indices. */
  184.         {
  185.           PUSH (left_ptr, hi);
  186.           hi = right_ptr;
  187.         }
  188.     }
  189.     }
  190.  
  191.   /* Once the BASE_PTR array is partially sorted by quicksort the rest
  192.      is completely sorted using insertion sort, since this is efficient
  193.      for partitions below MAX_THRESH size. BASE_PTR points to the beginning
  194.      of the array to sort, and END_PTR points at the very last element in
  195.      the array (*not* one beyond it!). */
  196.  
  197. #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
  198.  
  199.   {
  200.     int end_ptr = 0 + (total_elems - 1);
  201.     int run_ptr;
  202.     int tmp_ptr = 0;
  203.     int thresh = MIN (end_ptr, 0 + max_thresh);
  204.  
  205.     /* Find smallest element in first threshold and place it at the
  206.        array's beginning.  This is the smallest array element,
  207.        and the operation speeds up insertion sort's inner loop. */
  208.  
  209.     for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr += 1)
  210.       if (CMP (run_ptr, tmp_ptr) < 0)
  211.     tmp_ptr = run_ptr;
  212.  
  213.     if (tmp_ptr != 0)
  214.       SWAP (tmp_ptr, 0);
  215.  
  216.     /* Insertion sort, running from left-hand-side up to `right-hand-side.'
  217.        Pretty much straight out of the original GNU qsort routine. */
  218.  
  219.     for (run_ptr = 0 + 1; (tmp_ptr = run_ptr += 1) <= end_ptr;)
  220.       {
  221.  
  222.     while (CMP (run_ptr, tmp_ptr -= 1) < 0)
  223.       ;
  224.  
  225.     if ((tmp_ptr += 1) != run_ptr)
  226.       {
  227.         ROT (tmp_ptr, run_ptr);
  228.         /* int trav;
  229.  
  230.         for (trav = run_ptr + 1; --trav >= run_ptr;)
  231.               {
  232.                 char c = *trav;
  233.                 char *hi, *lo;
  234.  
  235.                 for (hi = lo = trav; (lo -= 1) >= tmp_ptr; hi = lo)
  236.                   *hi = *lo;
  237.                 *hi = c;
  238.               } */
  239.       }
  240.  
  241.       }
  242.   }
  243.   return 1;
  244. }
  245.  
  246.  
  247. #ifdef TEST_ME
  248. int buf[25] =
  249. {
  250.   1, 15, 37, 9, 100, 3, 14, 2, 88,
  251.   6, 97, 12, 34, 8, 92, 11, 15, 38,
  252.   16, 6, 93, 42, 45, 55, 64};
  253. main ()
  254. {
  255.   int com ();
  256.   void swa ();
  257.   void rot ();
  258.   int n;
  259.  
  260.   sort (25, com, swa, rot);
  261.   for (n = 0; n < 25; n++)
  262.     printf ("%d ", buf[n]);
  263. }
  264.  
  265. com (n1, n2)
  266. {
  267.   printf ("Cmp %d,%d\n", n1, n2);
  268.   return buf[n1] - buf[n2];
  269. }
  270.  
  271. void
  272. swa (n1, n2)
  273. {
  274.   int t;
  275.  
  276.   printf ("Swap %d,%d\n", n1, n2);
  277.   t = buf[n1];
  278.   buf[n1] = buf[n2];
  279.   buf[n2] = t;
  280. }
  281.  
  282. void
  283. rot (n1, n2)
  284. {
  285.   int t;
  286.  
  287.   printf ("Rot %d,%d\n", n1, n2);
  288.   t = buf[n2];
  289.   while (n2 > n1)
  290.     {
  291.       buf[n2] = buf[n2 - 1];
  292.       --n2;
  293.     }
  294.   buf[n2] = t;
  295. }
  296.  
  297. #endif
  298.